var redis = require('redis');
var config = global.config.redis[global.config.env];
var client = redis.createClient(config);

var isConnect = function(callback) {
	if (client.connected) {
		callback();
	} else {
		setTimeout(function() {
			isConnect(callback);
		}, 500);
	}
}

var Redis = {
	subscribe: function(key, callback) {
		isConnect(function() {
			client.subscribe(key, callback);
		});
	},
	publish: function(key, value, callback) {
		isConnect(function() {
			client.unsubscribe();
			client.publish(key, value, callback);
		});
	},
	hset: function(key, value, callback) {
		isConnect(function() {
			client.hset(key, value, callback);
		})
	},
	hget: function(key, value, callback) {
		isConnect(function() {
			client.hget(key, value, callback);
		})
	},
	set: function(key, value, callback) {
		isConnect(function() {
			client.set(key, value, callback);
		})
	},
	get: function(key, callback) {
		isConnect(function() {
			client.get(key, callback);
		})
	},
	hmset: function(key, value, callback) {
		isConnect(function() {
			client.hmset(key, value, callback);
		})
	},
	hmget: function(key, index, callback) {
		isConnect(function() {
			client.hmget(key, index, callback);
		})
	},
	hgetall: function(key, callback) {
		isConnect(function() {
			client.hgetall(key, callback);
		})
	},
	del: function(key, callback) {
		isConnect(function() {
			client.del(key, callback);
		})
	}
}

module.exports = Redis;